<template>
  <el-dialog
    v-model="show" class="login" width="560px" append-to-body title="用户登录"
    destroy-on-close :show-close="showClose" :close-on-click-modal="false"
  >
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <el-form-item prop="telno">
        <el-input
          v-model="loginForm.telno"
          type="number"
          size="large"
          auto-complete="off"
          placeholder="手机号"
        >
          <template #prefix>
            <svg-icon icon-class="user" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="captchaEnabled" prop="code">
        <el-input
          v-model="loginForm.code"
          size="large"
          auto-complete="off"
          placeholder="验证码"
          style="width: 70%"
          @keyup.enter="handleLogin"
        >
          <template #prefix>
            <svg-icon icon-class="validCode" class="el-input__icon input-icon" />
          </template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" class="login-code-img" @click="getCode">
        </div>
      </el-form-item>
      <el-form-item prop="captcha">
        <el-input
          v-model="loginForm.captcha"
          size="large"
          auto-complete="off"
          placeholder="短信验证码"
          @keyup.enter="handleLogin"
        >
          <template #append>
            <el-button v-if="showMsgBtn" type="danger" @click="getCaptchaSms">发送短信</el-button>
            <van-count-down
              v-show="!showMsgBtn" ref="countDown" :time="60000" format="ss s" :auto-start="false"
              @finish="onFinish"
            />
          </template>
        </el-input>
      </el-form-item>
      <!--      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住我</el-checkbox>-->
      <el-form-item style="width:100%;">
        <el-button
          class="loginBtn"
          :loading="loading"
          size="large"
          type="danger"
          style="width:100%;"
          @click.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
      <el-form-item>
        <span style="color: #999;font-size: 12px;">*未注册手机验证后自动登录，登录或注册即代表同意</span>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { getCodeImg } from '@/api/login'
import * as match from '@/api/match/pc'
import Cookies from 'js-cookie'
import useUserStore from '@/store/modules/user'
import { useRouter } from 'vue-router'
import { getCurrentInstance, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['submitForm'])
const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const loginForm = ref({
  telno: '',
  captcha: '',
  rememberMe: false,
  code: '',
  uuid: ''
})
const countDown = ref(null)
const loginRules = {
  telno: [{ required: true, trigger: 'change', message: '请输入您的手机号' }],
  captcha: [{ required: true, trigger: 'change', message: '请输入您的短信验证码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
}

const show = ref(false)
const showClose = ref(true)
const codeUrl = ref('')
const loading = ref(false)
const showMsgBtn = ref(true)
// 验证码开关
const captchaEnabled = ref(true)
// 注册开关
const register = ref(false)
const redirect = ref(undefined)

watch(show, (val) => {
  if (!val) {
    userStore.setReLogin(false)
  }
})

const open = (params) => {
  show.value = true
  showClose.value = !(params?.notShowClose || false)
  getCode()
}
defineExpose({
  open
})
function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set('telno', loginForm.value.telno, { expires: 30 })
        Cookies.set('rememberMe', loginForm.value.rememberMe, { expires: 30 })
      } else {
        // 否则移除
        Cookies.remove('telno')
        Cookies.remove('rememberMe')
      }
      // 调用action的登录方法
      userStore.loginPc(loginForm.value.telno, loginForm.value.captcha).then(() => {
        // router.push({ path: redirect.value || '/index' })
        show.value = false
        emit('submitForm')
      }).catch(() => {
        loading.value = false
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode()
        }
      })
    }
  })
}
function onFinish() {
  showMsgBtn.value = true
}
function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.data.img
      loginForm.value.uuid = res.data.uuid
    }
  })
}

function getCookie() {
  const telno = Cookies.get('telno')
  const rememberMe = Cookies.get('rememberMe')
  loginForm.value = {
    telno: telno === undefined ? loginForm.value.telno : telno,
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  }
}

function getCaptchaSms() {
  // 判断手机号正确
  if (!loginForm.value.telno) {
    ElMessage({
      showClose: true,
      message: '请输入手机号',
      type: 'error'
    })
    return
  }
  // 判断验证码填了没
  if (!loginForm.value.code) {
    ElMessage({
      showClose: true,
      message: '请输入验证码',
      type: 'error'
    })
    return
  }
  const strTemp = /^1[3|4|5|6|7|8|9][0-9]{9}$/
  if (strTemp.test(loginForm.value.telno)) {
    match.getCaptchaSms({
      uuid: loginForm.value.uuid,
      telno: loginForm.value.telno,
      code: loginForm.value.code
    }).then(res => {
      ElMessage({
        showClose: true,
        message: res.msg,
        type: 'info'
      })
      showMsgBtn.value = false
      countDown.value.start()
    })
  } else {
    ElMessage({
      showClose: true,
      message: '请输入正确的手机号',
      type: 'error'
    })
  }
}

getCode()
getCookie()
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.module.scss';
.ltitle {
  border-bottom: 1px solid #e1e1e1;
  color: $--color-primary;
  position: relative;
}

.ltitle::after {
  content: '';
  position: absolute;
  width: 4em;
  height: 2px;
  background: $--color-primary;
  left: 0;
  bottom: -1px;
}

.loginLogo {
  display: block;
  margin: auto;
  position: absolute;
  top: -80px;
  left: 0;
  right: 0;
}

.loginBtn {
  background: linear-gradient(270deg, $--color-primary, $--color-primary);
  height: 50px;
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.png");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  position: relative;
  background: #ffffff;
  padding: 0 50px 5px;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}

:deep(.el-input-group__append) {
  background: $--color-primary;
  color: #fff;
  div{color: #fff;}
}
</style>
